//
//  VediosViewController.m
//  XIWenLeJian
//
//  Created by lanou3g on 15/11/11.
//  Copyright © 2015年 蓝足. All rights reserved.
//

#import "VediosViewController.h"
#import "VideosTableViewCell.h"
#import "MJRefresh.h"
#import "VideoModel.h"
#import "NetWorkHandle.h"

@interface VediosViewController ()<UITableViewDataSource, UITableViewDelegate>

// 数据源数组
@property (nonatomic, strong)NSMutableArray *dataArray;

// cell
@property (nonatomic, strong)VideosTableViewCell *videoCell;

@property (nonatomic, assign)int upCount;

@end

@implementation VediosViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];

    [self netWorking:@"http://api.budejie.com/api/api_open.php?a=list&appname=baisishequ&asid=79C90406-DB8A-4758-9466-DEDB502C2A14&c=video&client=iphone&device=ios%20%E8%AE%BE%E5%A4%87&from=ios&jbk=0&mac=&market=&openudid=3739a3941c7bb4f82c78c8c53228edcb4a14f0d0&page=0&per=20&sub_flag=1&type=41&udid=&ver=3.6"];
  
    
#pragma mark>>>>>>>>>>>>下拉刷新
    // 设置回调, 一旦进入刷新状态, 就调用 target 的 action, 也就是调用self 的刷新方法
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(setUpRefresh)];
    
    // 设置文字
    [header setTitle:@"下拉刷新" forState:(MJRefreshStateIdle)];
    [header setTitle:@"松开释放" forState:(MJRefreshStatePulling)];
    [header setTitle:@"正在刷新..." forState:(MJRefreshStateRefreshing)];
    
    // 字体
    header.stateLabel.font = [UIFont systemFontOfSize:15];
    header.lastUpdatedTimeLabel.font = [UIFont systemFontOfSize:15];
    header.stateLabel.textColor = [UIColor grayColor];
    
    // 进入刷新状态
    [header beginRefreshing];
    
    // 设置刷新控件
    self.tableView.header = header;
    
#pragma mark>>>>>>>>>>>>>>> 上拉加载
    // 设置回调(一旦进入刷新状态就会调用这个refreshingBlock)
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    // 设置文字
    [footer setTitle:@"点击和上拉会加载更多" forState:(MJRefreshStateIdle)];
    [footer setTitle:@"正在加载更多" forState:(MJRefreshStatePulling)];
    [footer setTitle:@"没有更多了" forState:(MJRefreshStateNoMoreData)];
    
    // 字体
    footer.stateLabel.font = [UIFont systemFontOfSize:15];
    footer.stateLabel.textColor = [UIColor grayColor];
    self.tableView.footer = footer;
}

- (void)setUpRefresh
{
    // 把先前数据全部移除
    [self.dataArray removeAllObjects];
    // 解析数据
    [self netWorking:@"http://api.budejie.com/api/api_open.php?a=list&appname=baisishequ&asid=79C90406-DB8A-4758-9466-DEDB502C2A14&c=video&client=iphone&device=ios%20%E8%AE%BE%E5%A4%87&from=ios&jbk=0&mac=&market=&openudid=3739a3941c7bb4f82c78c8c53228edcb4a14f0d0&page=0&per=20&sub_flag=1&type=41&udid=&ver=3.6"];
    [self.tableView reloadData];
}


// 上拉加载
- (void)loadMoreData
{
    static int i = 2;
    i = i + 1;
    _upCount = i * 10;
   
    // 解析数据
    NSString *str1 = @"http://api.budejie.com/api/api_open.php?a=list&appname=baisishequ&asid=79C90406-DB8A-4758-9466-DEDB502C2A14&c=video&client=iphone&device=ios%20%E8%AE%BE%E5%A4%87&from=ios&jbk=0&mac=&market=&openudid=3739a3941c7bb4f82c78c8c53228edcb4a14f0d0&page=0&per=";
    NSString *str2 = @"&sub_flag=1&type=41&udid=&ver=3.6";
    NSString *str3 = [NSString stringWithFormat:@"%d", _upCount];
    NSString *str = [NSString stringWithFormat:@"%@%@%@", str1, str3, str2];
    [self netWorking:str];
    // 当拿到当前的下拉加载内容, 结束刷新状态
    [self.tableView.footer endRefreshing];
}

- (NSMutableArray *)dataArray
{
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)netWorking:(NSString *)urlStr
{
    [_dataArray removeAllObjects];
    [NetWorkHandle getDataWithURLString:urlStr compare:^ (id object){
        NSDictionary *dict = object;
        for (NSMutableDictionary *dic in dict[@"list"]) {
            VideoModel *model = [[VideoModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [_dataArray addObject:model];
        }
        
        [self.tableView.footer endRefreshing];
        [self.tableView.header endRefreshing];
        [self.tableView reloadData];
        if (_upCount >= 140) {
            [self.tableView.footer noticeNoMoreData];
        }
        
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    int height = [((VideoModel *)self.dataArray[indexPath.row]).height intValue];
    int width = [((VideoModel *)self.dataArray[indexPath.row]).width intValue];
    if (height * (self.view.frame.size.width - 40) / (width + 1) >= self.view.frame.size.width - 25) {
        return (height *(self.view.frame.size.width - 100) / (width + 1)) +70;
    }else{
        return (height * (self.view.frame.size.width) / (width + 1)) + 70;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *str = @"cell";
    _videoCell = [tableView dequeueReusableCellWithIdentifier:str];
    if (_videoCell == nil) {
        _videoCell = [[VideosTableViewCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:str];
    }
   
    _videoCell.model = _dataArray[indexPath.row];
    
    _videoCell.backgroundColor = [UIColor groupTableViewBackgroundColor];
    _videoCell.selectedBackgroundView = [[UIView alloc]init];
    
    __weak typeof (self) weakSelf = self;
    self.videoCell.reloadDataBlock = ^{
        [weakSelf.tableView reloadData];
    };
    
    // 播放
   self.videoCell.movieBlock = ^(NSString *str){
        NSURL *url = [NSURL URLWithString:str];
        weakSelf.player = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
        [weakSelf.player.moviePlayer setScalingMode:(MPMovieScalingModeNone)];
        [weakSelf.player.moviePlayer setControlStyle:MPMovieControlStyleFullscreen];
        [weakSelf.player.moviePlayer.backgroundView setBackgroundColor:[UIColor colorWithRed:1 green:1 blue:1 alpha:0.1]];
        [weakSelf.player.moviePlayer.backgroundView setFrame:weakSelf.view.bounds];
        // 注册一个播放结束的通知
        [[NSNotificationCenter defaultCenter]addObserver:weakSelf selector:@selector(end:) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
        // 弹出模态窗口(全屏)，播放视频。
        [weakSelf presentMoviePlayerViewControllerAnimated:weakSelf.player];
        // 用play 方法，电影播放控制器会自动将视图切换到电影播放器并开始播放
        [weakSelf.player.moviePlayer play];
    };
    return _videoCell;
}

// 播放完移除自己
- (void)end:(id)sender
{
    // 移除播放通知
    [[NSNotificationCenter defaultCenter]removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
    [self.player.view removeFromSuperview];
    // 释放资源
    self.player = nil;
    
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"aaaaa");
}

@end
